import './style/index.css'

import {Icon, Modal, Progress} from 'antd'
import RenderList from './RenderList'
import {WeaInput, WeaLocaleProvider, WeaNewScroll, WeaUpload, WeaTools,WeaDragula} from 'ecCom';

const confirm = Modal.confirm;
const getLabel = WeaLocaleProvider.getLabel; 
const deletFile = params => {
	return WeaTools.callApi('/api/doc/operate/delete', 'GET', params);
};
/**
 * 附件上传
 */
export default class Main extends React.Component{
	constructor(props) {
		super(props);
		this.state = {
			annexdocinfos:this.props.annexdocinfos||[],
			top:0,
			percent: 0, 
			speed: 500,
			status:''
		}
		
		this.FILE_LIST_ITEM_HEIGHT  = 28;
		this.FILE_LIST_SCROLL_ITEM_NUM = 4;
	}

	componentWillReceiveProps(nextProps) {
		const _top =  this.getphraseblockheight((nextProps.annexdocinfos.length-this.props.annexdocinfos.length),'add');
		this.setState({annexdocinfos:nextProps.annexdocinfos,top:_top});
	}

	//移入移除样式
    fnOnMouseOut(fileid,isrename, e) {
		if(isrename) {
            jQuery(e.currentTarget).find(".ic_"+fileid).css({"display":"none"});
            let obj = jQuery(e.currentTarget).find(`.div_msg_span${fileid}`).css({"width":"152px"});
		}
    }

    fnOnMouseOver(fileid, isrename, e) {
		if(isrename) {
            jQuery(e.currentTarget).find(".ic_"+fileid).css({"display":"inline"});
            let obj = jQuery(e.currentTarget).find(`.div_msg_span${fileid}`).css({"width":"127px"});
		}
    }

    //拖动完成
    onDrop=(refdr, refwd, newList)=>{
        //更新数据顺序，按照用户排序进行设置
        let idv = "",ok = false;
        try{
           if(Array.isArray(newList) ){//新上传数据后直接得到数据对象
               newList && newList.map((item, i)=>{//得到新的id序列
                   let thisid = item.fileid;
                   if(!ok) {
                       idv += thisid;
                       ok = true;
                   } else {
                       idv += "," + thisid;
                   }
               });
		   } else {//从后台得到初始数据得到的是dom对象，有问题，采用下面的解决方式
               let lists = jQuery("#"+refdr).find("li");
               let datas = this.refs[refwd].props.datas;
               newList = [];
               lists.map((i, item)=>{
                   if(!jQuery(item).hasClass("gu-mirror")) {
                       let thisid = jQuery(item).attr("idkey");
                       for(let i = 0;i < datas.length;i++) {
                           if(datas[i].fileid == thisid){
                               newList.push(datas[i]);
                               if(!ok) {
                                   idv += datas[i].fileid;
                                   ok = true;
                               } else {
                                   idv += "," + datas[i].fileid;
                               }
                               break;
                           }
                       }
                   }
               })
		   }
            const {changeRemarkInfo} = this.props;
            if(changeRemarkInfo)
                changeRemarkInfo({"field-annexupload": idv,annexdocinfos:newList});
		} catch (e) {

        }
	}

	//点击编辑按钮笔
	fnclickedit=(fileid, filename) =>{
        const {editorId} = this.props;
        let val = filename;
        if(filename.lastIndexOf(".") != -1) {
            val = filename.substring(0,filename.lastIndexOf("."));
		}
        jQuery(".dr_"+editorId+" .ipt_"+fileid).val(val).focus();
        jQuery(".dr_"+editorId+" .ipt_"+fileid).css({"display":"inline"});
        jQuery(".dr_"+editorId+" .ic_"+fileid).css({"display":"none"});
        jQuery(".dr_"+editorId+" .div_msg"+fileid).css({"display":"none"});
        jQuery(".dr_"+editorId+" .ipt_"+fileid).focus();

        var tObj =   this.refs["dr_"+editorId+"_"+fileid];
        var sPos = val.length;
        setCaretPosition(tObj, sPos);
        function setCaretPosition(tObj, sPos){
            if(tObj.setSelectionRange){
                setTimeout(function(){
                    tObj.setSelectionRange(sPos, sPos);
                    tObj.focus();
                }, 0);
            }else if(tObj.createTextRange){
                var rng = tObj.createTextRange();
                rng.move('character', sPos);
                rng.select();
            }
        }

    }

	//编辑完成
    fnOnBlurByInput1=( fileid, name, imagefileid, e) => {
        const {editorId} = this.props;
        jQuery(".dr_"+editorId+" .div_msg"+fileid).css({"display":"inline-block"})
        jQuery(".dr_"+editorId+" .ipt_"+fileid).css({"display":"none"});
		let newname = jQuery(".dr_"+editorId+" .ipt_"+fileid).val();
		let  fileNameReg = /[\\\\/:*?\"<>|]/g;
        if (fileNameReg.test(newname)) {//去掉非标准字符串
            newname = newname.replace(fileNameReg, "");
        }
		newname = newname.replace(/(^\s*)|(\s*$)/g, "");//去掉前后空格去掉
        let end = "";
        let oldname = name;
		if(name.lastIndexOf(".") != -1) {
            end = name.substring(name.lastIndexOf("."));
            oldname = name.substring(0,name.lastIndexOf("."));
		}
        if(newname === oldname || newname == "" || newname == undefined) {//判断是否发生改变,以及名称不能为空
        } else {
            const {annexdocinfos=[]} = this.state;
            annexdocinfos.map(item =>{
                if(item.fileid == fileid) {
                    item.filename = newname+end;
                }
            })
            this.setState({annexdocinfos:annexdocinfos});
            this.props.onChange && this.props.onChange("Upload",'',annexdocinfos,'file');
            WeaTools.callApi("/api/doc/acc/rename","POST",{imagefileid:imagefileid,imagefilename:newname+end});//该数据库名称
            this.props.updateWeaRichText(newname+end, fileid);
		}
    }

    renderlistB = (list)=>{
        const {isdragula = false,isrename=false,editorId} = this.props;
        return (
            <ul ref={"dr_"+editorId} id={"dr_"+editorId} className={"wf_upload_css_cc"} style={{ padding: list.length > 0 ? "0 0 5px 0" : 0 }} >
                {list.map(item=>{
                	const {fileid, filename, imagefileid} = item;
                    return (
						<li className={"dr_"+editorId} key={fileid} idkey={fileid}>
                            <div onMouseOver={this.fnOnMouseOver.bind(this, fileid, isrename)}  onMouseOut={this.fnOnMouseOut.bind(this, fileid, isrename)} >
                                <div style={{float: "left"}} className={"li-filename"}>
                                    {isdragula?<span data-index={fileid} title={getLabel(504625,"拖拽")} key={fileid} className="icon-coms-move cursor-pointer imgpad5" />:null}
                                    <span className={"div_msg div_msg"+item.fileid}>
                                        <span onClick={this.onAddUploadFile.bind(this,fileid)} title={filename}  className={"div_msg_span div_msg_span"+fileid} >{filename}</span>
                                        {isrename? (
                                            <i
                                                className={"icon-coms-edit cursor-pointer imgpad5 hidde_css ic_" + fileid}
												style={{'fontSize':'12px'}}
                                                onClick= {this.fnclickedit.bind(this, fileid, filename)} //可编辑图标
                                                title={getLabel(93,"编辑")}
                                            />
                                        ) : null}
                                    </span>
                                    <input type="text" ref={"dr_"+editorId+"_"+fileid} className={"hidde_css ipt_"+fileid} title={"文件名不能包含\\ \/ : * ? \" < > | "}
										   onBlur={this.fnOnBlurByInput1.bind(this,fileid, filename, imagefileid)}/>
                                </div>
                                <div >
                                    <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@31mcjl@${fileid}`} type="cross" title={getLabel(91, "删除")} onClick={this.onDeleteUploadFile.bind(this,item)}/>
                                </div>
                            </div>
						</li>
					);
				})}
			</ul>
		)
	}
	render(){
		const {annexdocinfos=[],top,percent,speed,status} = this.state;
		const {visible} = this.props;
		const {category,annexmaxUploadImageSize,editorId,isdragula = true,isrename=true} = this.props;
		const filecontentheight  =  annexdocinfos.length > this.FILE_LIST_SCROLL_ITEM_NUM ? (this.FILE_LIST_ITEM_HEIGHT * this.FILE_LIST_SCROLL_ITEM_NUM):(annexdocinfos.length*this.FILE_LIST_ITEM_HEIGHT);
		let  _top = top;
		if(visible && top == 0){
			_top = this.getphraseblockheight(annexdocinfos.length);
		}

        let baseProps={};
		let params= {};//自定义参数，主要是判断是否为流程草稿
        // //字段是否开启拖拽， 后台是否开启拖拽，文件是否可编辑
        baseProps.editable = isrename;//重命名
        baseProps.issortable = isdragula;//拖拽
		baseProps.maxUploadSize = annexmaxUploadImageSize;
        if(true){
            params.isFirstUploadFile = "9";//流程草稿
		}
		return (
			<div className="wea-ckeditor-fileupload">
	        	<div className="wea-cb-item" onClick={this.showUploadedInfo} title={`${getLabel(385751,'附件上传(最大')}${annexmaxUploadImageSize}M/${getLabel(27591,'个')})`}>
				     <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@ifrzt3`} className="wea-cbi-icon" type="paper-clip" >
				     	{annexdocinfos.length > 0 && <div className="red-point"></div>}
				     </Icon>
				    <span className="wea-cbi-text">{getLabel(156,'附件')}</span>
		        </div>
				<div className={"fileupload-phraseblock div_"+editorId} style={{display:visible?'block':'none',top:_top}}>
					<iframe className="wf-fileupload-iframe"></iframe>
					<div className="file-content-block">
						{annexdocinfos.length > 0 && 
							<WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@ihysgc`} height={filecontentheight+5}>
                                <WeaDragula ecId={`${this && this.props && this.props.ecId || ''}_WeaDragula@rxclsv`}
									ref={"wd_"+editorId}
									container={()=>this.refs["dr_"+editorId]}
									canDrag={(target) => {
                                        const modal = jQuery(".wea-req-forward-modal").find(".react-draggable");
                                        modal.length === 1 && (modal[0].style.transform = "inherit");
										return jQuery(target).hasClass("icon-coms-move");
                                    }}
									datas={annexdocinfos}
									getKeyFromData={ record => record.fileid}
									getKeyFromDom={r =>  jQuery("span.icon-coms-move", r).attr("data-index")}
									onDrop={( ...arg) => this.onDrop("dr_"+editorId,"wd_"+editorId, ...arg)}
								>
									{this.renderlistB(annexdocinfos)}
								</WeaDragula>

								{/*<ul className={"sortable"}>
								{
									annexdocinfos.map(item=>{
										return  <li onClick={this.onAddUploadFile.bind(this,item.fileid)}>
													<span className="li-filename" title={item.filename}>{item.filename}</span>
													<Icon type="cross" onClick={this.onDeleteUploadFile.bind(this,item)}/>
												</li>
									})
								}
								</ul>*/}
							</WeaNewScroll>
						}
					</div>
					<div className="file-upload-btn">
						<WeaUpload ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@aw0p0n`} uploadUrl={`/api/doc/upload/uploadFile2Doc?category=${category}`}
								   uploadId={`${editorId}_phraseupload`}
								   category={category}
					               onChange={this.onFileUploadChange}
					               datas={annexdocinfos}
					               style={{padding:0}}
					               RenderList={RenderList}
                                   uploadParams={params}
								   {...baseProps}
								   >
								<Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@vb26ru`} type="plus-circle-o"/>
						</WeaUpload>
					</div>
					<div className="triangle_border_nw" style={{display:visible?'block':'none'}}></div>
				</div>
			</div>
		)
	}
	
	showUploadedInfo = () => {
		const {visible} = this.props;
		const _top =  this.getphraseblockheight();
		this.setState({top:_top});
		this.props.showComponent(visible ? '':'Upload')
	}
	
	onAddUploadFile(fileid){
		const {annexdocinfos} = this.state;
		this.props.onChange && this.props.onChange("Upload",'',annexdocinfos,'file',fileid);
	}
	
	onDeleteUploadFile(o,e){
		const _this = this;
		confirm({
			content:`${getLabel(84051,'确定要删除')}${o.filename}${getLabel(385752,'吗')}?`,
			zIndex:1050,
			onOk(){
				try{
					const fileid  = o.fileid;
					const {annexdocinfos} = _this.state;
					let _annexdocinfos = annexdocinfos.filter(item=> item.fileid != fileid);
					const _top =  _this.getphraseblockheight(1,'del');
					_this.setState({annexdocinfos:_annexdocinfos,top:_top});
                    _this.props.updateWeaRichText("", fileid);//同时删除签字意见中的附件内容，
					_this.props.onChange && _this.props.onChange("Upload",'',_annexdocinfos,'file',"","del");
					deletFile({docid:fileid});
				}catch(e){console.log(e)}
			}
		});
		e.stopPropagation();
	}
	
	getphraseblockheight(num=0,type=''){
		const {annexdocinfos} = this.state;
		let docs = annexdocinfos.length;
		if(type == 'del') {
			docs = docs - num;
		}else if(type == 'add'){
			docs = docs + num;
		}
		docs  = docs  > 4 ? 4:docs;
		if(docs === 0) return -53;
		return -(this.FILE_LIST_ITEM_HEIGHT * docs + 57);
	}
	
	onFileUploadChange = (ids, list=[]) => {
		const {annexdocinfos} = this.state;
		const _top =  this.getphraseblockheight((list.length - annexdocinfos.length),'add');
		this.setState({annexdocinfos:list,top:_top});
		this.props.onChange && this.props.onChange("Upload",'',list,'file');
	}
}